<template>
	<!--线下课核销页-->
	<view :class="config.style">
		<FullscreenLoading :loading="loading" :config="config"></FullscreenLoading>
		<!-- #ifdef H5-->
		<Top :config="config"></Top>
		<!-- #endif -->
		<view class="main-section top">
			<view class="content">
				<view class="cover">
					<image mode="widthFix" :src="data.cover_200" class="image"></image>
				</view>
				<view class="info">
					<view class="title text-ellipsis-2">{{data.title}}</view>
					<view class="description">
						<text>{{data.description}}</text>
					</view>
				</view>
			</view>
			
			<view class="time-and-address">
				<view class="time">
					<view class="icon">
						<text class="iconfont">&#xe60e;</text>
					</view>
					<view class="info">
						{{data.lessons_start_time_str}} - {{data.lessons_end_time_str}}
					</view>
				</view>
				<view class="address" @click="goToMapPage(data.point)">
					<view class="icon">
						<text class="iconfont">&#xe633;</text>
					</view>
					<view class="info text-ellipsis">
						{{data.province}} {{data.district}} {{data.city}} {{data.address}}
					</view>
					<view class="active">
						<uni-icons type="arrowright" size="14" color="#999999"></uni-icons> 
					</view>
				</view>
			</view>
			
			<view class="list-section">
				<!-- top="xxx"下拉布局往下偏移,防止被悬浮菜单遮住 -->
				<mescroll-uni ref="mescrollRef" @init="mescrollInit" :top="mescrolTop" :down="downOption" @down="downCallback" @up="upCallback">
					<!-- 数据列表 -->
					<view class="list">
						<view class="item" v-for="(item,index) in list" :key="index">
							<view class="info">
								<view class="title text-ellipsis">
									{{item.lessons.title}}
								</view>
								<view class="start-time">
									<text class="tit">开课时间：</text>
									<text class="time">{{item.lessons.start_time_str}}</text>
								</view>
								<view class="status" :class="item.status==1?'status1':'status0'">
									{{item.status_str}}
								</view>
							</view>
							<view class="action">
								<button v-if="item.status==0" type="default" size="mini" class="verify-button" hover-class="button-hover" @click="showQrcode(item.id)">
									核销码
								</button>
								<button v-if="item.status==1" type="default" size="mini" class="info-button" hover-class="button-hover" @click="goToAction(item.id)">
									核销详情
								</button>
							</view>
						</view>
					</view>
				</mescroll-uni>
			</view>
		</view>
		
		
		<uni-popup ref="openQrcode" type="center" :mask-click="false">
			<view class="open-qrcode">
				<!--显示核销码码-->
				<view class="content">
					<view class="title">核销码</view>
					<view class="qrcode">
						<!-- #ifdef MP-WEIXIN -->
						<TkiQrcode cid="qrcode1" ref="qrcode" :val="qrcodeUrl" :size="size" :unit="unit" :background="background" :foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconsize" :lv="lv" :onval="onval" :loadMake="loadMake" :usingComponents="true" @result="qrR" />
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<image :src="qrcodeUrl" class="image"></image>
						<!-- #endif -->
					</view>
				</view>
				<view class="close-icon" @click="closeQrcode()">
					<text class="iconfont">&#xe622;</text>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	//全屏加载中
	import FullscreenLoading from '../../../components/muu-fullscreen-loading/muu-fullscreen-loading.vue'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"
	import Top from '../common/top.vue'
	import TkiQrcode from '@/components/tki-qrcode/tki-qrcode.vue'
	
	export default {
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		components: {
			FullscreenLoading,
			Top,
			TkiQrcode
		},
		data() {
			return {
				loading: true,
				urlParams: {}, 
				userInfo : {}, //用户数据
				data: {}, // 课程详情数据
				page: 1, // 初始页码
				list: [],
				mescrolTop: 288,
				downOption: {
					auto: false //是否在初始化后,自动执行downCallback; 默认true
				},
				qrcodeUrl: '',  //课节核销码地址 要生成的二维码值
				size: 460, // 二维码大小
				unit: 'upx', // 单位
				background: '#ffffff', // 背景色
				foreground: '#000000', // 前景色
				pdground: '#32dbc6', // 角标色
				icon: '', // 二维码图标
				iconsize: 40, // 二维码图标大小
				lv: 3, // 二维码容错级别 ， 一般不用设置，默认就行
				onval: false, // val值变化时自动重新生成二维码
				loadMake: false, // 组件加载完成后自动生成二维码
				src: '' ,// 二维码生成后的图片地址或base64
				intervalId: null, // 轮询对象
			}
		},
		
		async onLoad(option) { //option为object类型，会序列化上个页面传递的参数
		    await this.$onLaunched;
			this.urlParams = option
			console.log(this.urlParams)
			Promise.all([this.getData()]).then(res => {
				//加载完成
				this.loading = false
			})
			console.log(this.$refs.qrcode)
		},
		created() {
			//获取已登录用户数据
			//this.getUserInfo()
			//#ifdef H5
			this.mescrolTop = this.mescrolTop + 70
			//#endif
		},
		computed: {
			...mapState(['config'])
		},
		onUnload() {
			if(this.intervalId) {
				clearInterval(this.intervalId)
				this.intervalId = null
			}
		},
		onHide() {
			if(this.intervalId) {
				clearInterval(this.intervalId)
				this.intervalId = null
			}
		},
		destroyed() {
			if(this.intervalId) {
				clearInterval(this.intervalId)
				this.intervalId = null
			}
		},
		methods: {
			/**
			 * 获取课程详情数据
			 */
			getData: function(){
				let that = this
				return new Promise((resolve, reject) => {
					let params = this.urlParams
					let data = {}
						data.action = 'detail'
						data.id = params.id
						
					//获取数据
					let url = '';
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/offline'
						//#endif
						//#ifdef H5
						url = 'entry/site/offline'
						data.m = 'muu_classroom_plugin_offline'
						//#endif
					this.util.request({
						url : url,
						data : data,
						success: function (res) {
							if (res.data.code == 200) {
								that.data = res.data.data
								uni.setNavigationBarTitle({
								　　title:res.data.data.title
								})
							}
							resolve(res.data)
						}
					})
				})
			},
			
			/**
			 * 进入地图页面
			 * @param {Object} latitude
			 * @param {Object} longitude
			 */
			goToMapPage: function(){
				let that = this
				let point = this.data.point.split(",");// 在每个逗号(,)处进行分解。
				console.log(point)
				let latitude = parseFloat(point[1])
				let longitude = parseFloat(point[0])
				let name = '上课地址'
				let address = this.data.province + this.data.district + this.data.city + this.data.address
				// #ifdef MP-WEIXIN
				uni.openLocation({
					latitude: latitude,
					longitude: longitude,
					name: name,
					address: address,
					success: ()=> {
						console.log('success');
					},
					fail: ()=> {
						uni.showModal({
							content: '打开地图失败,请重试'
						})
					},
				})
				// #endif
				
				// #ifdef APP-PLUS
				let urlParams = 'latitude='+latitude+'&longitude='+longitude
				let url = '../map/map?' + urlParams
				console.log(url)
				//指定跳转地址
				uni.navigateTo({
					url: url
				});
				// #endif
			},
			
			//上拉加载的回调
			upCallback: function() {
				let that = this
				let data = {}
					data.products_id = this.urlParams.id
					data.page = this.page
				//获取首页数据
				let url = '';
					//#ifdef MP-WEIXIN
					url = 'entry/wxapp/offline'
					data.action = 'verification'
					data.m = 'muu_classroom'
					//#endif
					//#ifdef H5
					url = 'entry/site/verification'
					data.action = 'lists'
					data.m = 'muu_classroom_plugin_offline'
					//#endif
				//获取首页数据
				this.util.request({
					url : url,
					data : data,
					success: function (res) {
						//console.log(res.data.code);
						if (res.data.code == 200) {
							let list = res.data.data.data
							that.list = that.list.concat(list);
							//联网成功的回调,隐藏下拉刷新和上拉加载的状态;
							that.mescroll.endSuccess(list.length);
							that.page = that.page + 1
						}
					}
				})
			},
			
			//下拉刷新
			downCallback: function() {
				let that = this
				this.page = 1
				let data = {}
					data.products_id = this.urlParams.id
				let url = '';
					//#ifdef MP-WEIXIN
					url = 'entry/wxapp/offline'
					data.action = 'verification'
					data.m = 'muu_classroom'
					//#endif
					//#ifdef H5
					url = 'entry/site/verification'
					data.action = 'lists'
					data.m = 'muu_classroom_plugin_offline'
					//#endif
				//获取分页列表首页数据
				this.util.request({
					url : url,
					data : data,
					success: function (res) {
						if (res.data.code == 200) {
							that.list = []
							that.list = res.data.data.data
							//联网成功的回调,隐藏下拉刷新和上拉加载的状态;
							that.mescroll.endSuccess(that.list.length);
							that.page = 2
							console.log(that.list)
						}
					}
				})
			},
			
			/**
			 * 显示核销码
			 */
			showQrcode(id) {
				uni.showLoading({
				    title: '加载中'
				});
				let that = this
				that.qrcodeUrl = ''
				
				// 获取核销二维码地址
				let data = {}
					data.id = id
				let url = '';
					//#ifdef MP-WEIXIN
					url = 'entry/wxapp/offline'
					data.action = 'qrcode'
					data.m = 'muu_classroom'
					//#endif
					//#ifdef H5
					url = 'entry/site/verification'
					data.action = 'qrcode'
					data.m = 'muu_classroom_plugin_offline'
					//#endif
				this.util.request({
					url : url,
					data : data,
					success: function (res) {
						uni.hideLoading();
						if (res.data.code == 200) {
							let qrcode_url = res.data.data
							// 生成核销二维码
							that.qrcodeUrl = qrcode_url
							that.$refs.openQrcode.open()
							console.log(that.qrcodeUrl)
							//#ifdef MP-WEIXIN
							that.$nextTick(() => {
								that.creatQrcode()
							})
							//#endif
							
							//轮询等待核销结果
							 that.intervalId = setInterval(function(){
								//console.log(api);
								console.log('等待处理结果');
								that.verifyLoop(id)
							},2000)
						}
					}
				})
			},
			
			/**
			 * 生成二维码，目前仅在小程序内有效
			 */
			creatQrcode() {
				this.$refs.qrcode._makeCode()
			},
			qrR(res) {
				this.src = res
			},
			clearQrcode() {
				this.$refs.qrcode._clearCode()
				this.qrcodeUrl = ''
			},
			/**
			 * 关闭核销二维码
			 */
			closeQrcode: function(){
				this.$refs.openQrcode.close()
				if(this.intervalId) {
					clearInterval(this.intervalId)
					this.intervalId = null
				}
			},
			
			/**
			 * 轮询核销结果
			 */
			verifyLoop(id) {
				let that = this
				// 获取核销二维码地址
				let data = {}
					data.id = id
				let url = '';
					//#ifdef MP-WEIXIN
					url = 'entry/wxapp/offline'
					data.action = 'qrcode'
					data.m = 'muu_classroom'
					//#endif
					//#ifdef H5
					url = 'entry/site/verification'
					data.action = 'qrcode'
					data.m = 'muu_classroom_plugin_offline'
					//#endif
				this.util.request({
					url : url,
					data : data,
					method: 'POST',
					success: function (res) {
						console.log(res)
						//核销完成后
						if(res.data.code == 200){
							//弹出提示
							uni.showToast({
							    title: res.data.msg,
							    duration: 2000
							});
							//重新加载数据
							that.downCallback()
							//关闭核销二维码
							that.closeQrcode()
						}
					},
				})
			},
			
			/**
			 * 进入核销结果页
			 * @param {Object} id
			 */
			goToAction(id) {
				let urlParams = 'id='+id
				let url = 'action?' + urlParams
				console.log(url)
				//指定跳转地址
				uni.navigateTo({
				    url: url
				});
			},
			
			imageError: function(e) {
				console.error('image发生error事件，携带值为' + e.detail.errMsg)
			}
		}
	}
</script>

<style lang="scss">
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #f8f8f8;
		min-height: 100%;
		height: auto;
	}
	
	.content {
		background-color: #fff;
		padding: 5px;
		display: flex;
		flex-wrap: wrap;
		.cover {
			width: 180rpx;
			border-radius: 5px;
			overflow: hidden;
			.image {
				width: 100%;
				height: auto;
				display: block;
			}
		}
		.info {
			padding-left: 20rpx;
			.title {
				font-size: 30rpx;
				color: #000;
				font-weight: 600;
				height: 36px;
				line-height: 36rpx;
			}
			.description {
				color: #999;
				font-size: 24rpx;
			}
		}
	}
	
	.time-and-address {
		background-color: #fff;
		margin-bottom: 16rpx;
		font-size: 24rpx;
		color: #999;
		padding: 10rpx 0;
		.time {
			display: flex;
			padding: 10rpx 20rpx;
			
			.icon {
				width: 40rpx;
			}
			.info {
				flex: 1
			}
		}
		.address {
			display: flex;
			padding: 10rpx 20rpx;
			.icon {
				width: 40rpx;
			}
			.info {
				flex: 1
			}
			.active {
				width: 40rpx;
			}
		}
	}
	
	.list-section {
		.list {
			.item {
				display: flex;
				margin: 20rpx;
				padding: 10rpx;
				background-color: #fff;
				border-radius: 5rpx;
				height: 126rpx;
				overflow: hidden;
				.info {
					flex: 1;
					.title {
						font-size: 28rpx;
						color: #000;
						font-weight: 700;
					}
					.start-time {
						color: #999;
						.tit {
							font-size: 24rpx;
						}
						.time {
							font-size: 24rpx;
						}
					}
					.status.status0 {
						color: $LightRed;
						font-size: 24rpx;
					}
					.status.status1 {
						color: $Green;
						font-size: 24rpx;
					}
				}
				.action {
					width: 190rpx;
					text-align: center;
					button {
						width: 188rpx;
						margin-top: 40rpx;
					}
					.verify-button {
						background-color: $Blue;
						color: #fff;
						&::after {
							border: 0;
						}
					}
					.info-button {
						background-color: #fff;
						color: #ff6600;
						&::after {
							border: 2rpx solid #ff6600;
						}
					}
				}
			}
		}
	}
	
	.open-qrcode {
		
		.content {
			background-color: #fff;
			border-radius: 10rpx;
			overflow: hidden;
			width: 480rpx;
			padding: 20rpx;
			display: block;
			.title {
				text-align: center;
				font-size: 32rpx;
				font-weight: 700;
				line-height: 52rpx;
			}
			.qrcode {
				text-align: center;
			}
			.image {
				max-width: 100%;
				z-index: 999;
			}
		}
		.close-icon {
			padding-top: 32rpx;
			text-align: center;
			color: #fff;
			.iconfont {
				font-size: 64rpx;
			}
		}
	}
</style>
